<template>
  <div class="m-read-more-line">
    <div class="u-wrap" :style="style">
      <div class="u-content" ref="contentRef">
        <slot></slot>
      </div>
    </div>
    <m-read-more-bar
      v-show="isOverLimit"
      :collapsed="!showAll"
      @click="showAll = !showAll"
    ></m-read-more-bar>
  </div>
</template>

<script setup name="ReadMoreLine">
import { computed, ref } from 'vue'
import { watch } from 'vue'

const props = defineProps({
  limit: {
    type: Number,
    default: 1,
  },
  lineHeight: {
    type: Number,
    default: 20,
  },
})

const contentRef = ref()
// 是否超高
const isOverLimit = ref(false)
// 是否处于展开状态
const showAll = ref(false)

const style = computed(() => {
  const obj = {}
  if (isOverLimit.value && showAll.value === false) {
    obj.height = `${props.limit * props.lineHeight}px`
  } else {
    obj.height = `${contentRef.value?.offsetHeight}px` ?? 'auto'
  }
  obj.lineHeight = `${props.lineHeight}px`
  return obj
})

// 检查是否超高
function checkOverLimit() {
  if (contentRef.value) {
    isOverLimit.value = contentRef.value.offsetHeight > props.limit * props.lineHeight
  }
}

watch(
  [() => props.content, contentRef],
  () => {
    checkOverLimit()
  },
  { immediate: true }
)
</script>

<style lang="stylus" scoped>
.m-read-more-line
  position relative
  .u-wrap
    overflow hidden
    transition all .3s
  .u-more-wrap
    cursor pointer
    .u-angle
      transform rotate(180deg)
  .u-less-wrap
    cursor pointer
  .u-angle
    margin 0 auto
    width: 16px;
    height: 16px;
    background-size 100%
</style>
